/**
 *    Copyright (C) 2007-2009 DIVIS GmbH (http://www.divis-hagen.de/)
 * 
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 3 of the License, or (at your option) any later version.
 * 
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General
 *    Public License along with this library; if not, write to the
 *    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *    Boston, MA 02110-1301 USA
 */

package de.divis_hagen.json;


/**
 *
 * @author Aike J Sommer
 */
public class TreeWalker {
    
    private JSONContextImpl context;
    private JSONTree tree;

    public TreeWalker(JSONContextImpl context, JSONTree tree) {
        this.context = context;
        this.tree = tree;
    }
    
    public void walk(TreeAction action) throws JSONException {
        JSONObjectBase root = tree.getRoot();
        if (context.isUnwrap() && (root instanceof JSONObject)) {
            String name = ((JSONObject)root).getNames().iterator().next();
            root = ((JSONObject)root).get(name);
        }
        action.beginTree(root);
        walk(action, root, null);
        action.endTree(root);
    }
    
    private void walk(TreeAction action, JSONObjectBase o, String name) throws JSONException {
        action.beginElement(o, name);
        if (o instanceof JSONArray) {
            walkArray(action, (JSONArray) o);
        } else if (o instanceof JSONObject) {
            walkObject(action, (JSONObject) o);
        }
        action.endElement(o, name);
    }
    
    private void walkArray(TreeAction action, JSONArray array) throws JSONException {
        for (int i = 0; i < array.size(); i++) {
            JSONObjectBase o = array.get(i);
            walk(action, o, null);
        }
    }
    
    private void walkObject(TreeAction action, JSONObject object) throws JSONException {
        for (String name : object.getNames()) {
            walk(action, object.get(name), name);
        }
    }
    
}
